const pkg = require('../package.json');
const _ = require('lodash');
const helper = require('./extend/helper');

let saas = Object.create(_);
saas = Object.assign(saas, helper);

saas.version = pkg.version;

saas.ROOT_PATH = process.cwd();

saas.tableName = function (tableName, prefix = true) {
  if (saas.isBoolean(prefix)) {
    if (prefix) {
      const p = saas.config['tableNamePrefix'];
      return p ? p + '_' + tableName : tableName;
    } else {
      return tableName;
    }
  } else if (saas.isString(prefix)) {
    return prefix + '_' + tableName;
  } else {
    return tableName;
  }
}

saas.checkDbProp = function (tableName, obj) {
  const data = saas.schema[tableName];
  if (helper.isEmpty(data)) {
    return null;
  }
  if (helper.isObject(obj)) {
    for (let prop in obj) {
      if (!data.hasOwnProperty(prop)) {
        delete obj[prop];
      }
    }
  } else if (helper.isArray(obj)) {
    for (let item of obj) {
      for (let prop in item) {
        if (!data.hasOwnProperty(prop)) {
          delete item[prop];
        }
      }
    }
  }
  return obj;
};

saas.domain = function (path, ...params) {
  if (!path.startsWith('/')) {
    path = '/' + path;
  }
  let instance = require(saas.ROOT_PATH + '/domain' + path);
  if (helper.isFunction(instance)) {
    instance = new instance(...params);
  }
  if (this.data) {
    instance.data = this.data;
  }
  return instance;
};

saas.service = function (path, ...params) {
  if (!path.startsWith('/')) {
    path = '/' + path;
  }
  let instance = require(saas.ROOT_PATH + '/service' + path);
  if (helper.isFunction(instance)) {
    instance = new instance(...params);
  }
  if (this.data) {
    instance.data = this.data;
  }
  return instance;
};

saas.model = function (path, ...params) {
  if (!path.startsWith('/')) {
    path = '/' + path;
  }
  let instance = require(saas.ROOT_PATH + '/model' + path);
  if (helper.isFunction(instance)) {
    instance = new instance(...params);
  }
  if (this.data) {
    instance.data = this.data;
  }
  return instance;
};

module.exports = saas;
